import BaseSprite from "../../../Script/Base/BaseSprite";
import { EBundleType, EResType } from "../../../Script/Common/Enum";
import GameUtil from "../../../Script/Util/GameUtil";
import { LoadUtil } from "../../../Script/Util/LoadUtil";
import MarketUI, { IMarketItem } from "./MarketUI";

const { ccclass, property } = cc._decorator;

@ccclass
export default class MarketItem extends BaseSprite {

    @property({ type: cc.Sprite, tooltip: "" })
    private bg: cc.Sprite = null;
    @property({ type: cc.Node, tooltip: "" })
    private add: cc.Node = null;

    @property({ type: cc.Node, tooltip: "" })
    private iconRoot: cc.Node = null;
    @property({ type: cc.Sprite, tooltip: "" })
    private icon: cc.Sprite = null;
    @property({ type: cc.Label, tooltip: "" })
    private labName: cc.Label = null;
    @property({ type: cc.Label, tooltip: "" })
    private labSale: cc.Label = null;

    private data: IMarketItem = null;

    public setData(data: IMarketItem) {
        // console.log(data);

        this.data = data;
        this.labName.string = `${data.name}x${data.num}`;
        this.labSale.string = `售价: ${data.sale}`;

        this.add.active = data.itemId < 0;
        this.iconRoot.active = !(data.itemId < 0);
        // 更新icon
        if (data.itemId > 0) {
            LoadUtil.instance.setSpriteFrame(this.icon, EResType.Item, data.itemId, 100, 100);
        }

        // 背景框
        const self = this;
        const name = (data.id === 2 || data.id === 5) ? 'wupinkuang1' : 'wupinkuang2';
        self.bg.node.scaleX = (data.id === 1 || data.id === 4) ? -1 : 1;
        LoadUtil.instance.loadRes(EBundleType.Game, `res/market/texture/${name}`, cc.SpriteFrame, (err, res) => {
            if (err) {
                return;
            }
            if (res instanceof cc.Texture2D) {
                self.bg.spriteFrame = new cc.SpriteFrame(res);
                self.bg.node.width = res.width;
                self.bg.node.height = res.height;
            } else {
                self.bg.spriteFrame = res;
            }
        });
    }

    public refresh() {
        const sale = this.data.sale + this.data.sale / 2 * MarketUI.instance.addCount;
        this.labSale.string = `售价: ${sale}`;
    }

    private onSelectBtnClicked(event, eventData) {
        // console.log("当前点击的是:", this.data);
        if (this.data?.itemId < 0) {
            MarketUI.instance.clickStallId = this.data.id;
            MarketUI.instance.showBagViewAnim();
        }
    }
}